package org.misty.blog.service.impl;

import org.misty.blog.dao.CommentRepository;
import org.misty.blog.po.Comment;
import org.misty.blog.service.CommentService;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class CommentServiceImpl implements CommentService {
    private final CommentRepository commentRepository;

    public CommentServiceImpl(CommentRepository commentRepository) {
        this.commentRepository = commentRepository;
    }

    @Override
    public List<Comment> listCommentByArticleId(Long articleId) {
        List<Comment> comments = commentRepository.findByArticleId(articleId, Sort.by(Sort.Direction.DESC, "createTime"));
        return comments;
    }

    @Transactional
    @Override
    public Comment saveComment(Comment comment) {
        Long parentId = comment.getParent().getId();
        comment.setParent(null);
        if (parentId != -1) {
            Optional<Comment> opt = commentRepository.findById(parentId);
            opt.ifPresent(comment::setParent);
        }
        comment.setCreateTime(new Date());
        return commentRepository.save(comment);
    }
}
